package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.AlbumForm;
import com.springboot.cloud.demos.entity.po.Album;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class AlbumService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody AlbumForm albumForm) {
        return restTemplate.postForEntity("http://producer/album", albumForm, Result.class).getBody();
    }

    @SentinelResource(fallback = "updateFallback")
    public Result update(@RequestBody Album album) {
        AlbumForm albumForm = new AlbumForm();
        BeanUtils.copyProperties(album, albumForm);
        restTemplate.put("http://producer/album/{1}", albumForm, albumForm.getId());
        return Result.success();
    }

    @SentinelResource(fallback = "getAlbumFallback")
    public Result<List<Album>> getAlbum(@RequestParam("momentId") String momentId) {
        return restTemplate.getForEntity("http://producer/album?momentId={1}", Result.class, momentId).getBody();
    }

    @SentinelResource(fallback = "getAlbumFallback")
    public Result get(@PathVariable String id) {
        return restTemplate.getForEntity("http://producer/album/{1}", Result.class, id).getBody();
    }

    public Result saveFallback(@RequestBody AlbumForm albumForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result getAlbumFallback(String uid, String unitId) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }


    public Result updateFallback(Album album) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }


    public Result deleteByUrlFallback(AlbumForm albumForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result deleteFallback(String id) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "deleteByUrlFallback")
    public Result deleteByUrl(AlbumForm albumForm) {
        restTemplate.postForEntity("http://producer/album/deleteByUrl", albumForm, Result.class);
        return Result.success();
    }

    @SentinelResource(fallback = "deleteFallback")
    public Result delete(@PathVariable String id) {
        restTemplate.delete("http://producer/album/" + id);
        return Result.success();
    }
}
